<template>
  <div class="form">
    <p class="title">用户入坟</p>
    <el-form
      :model="loginData"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="loginData.userName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginData.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import routers from "../../../router/routers";
import { FilterRoutes } from "../../../utils/tools";
import { LOGIN } from "../../../store/actionType";
import { createNamespacedHelpers } from "vuex";
let { mapActions, mapState } = createNamespacedHelpers("user");
export default {
  data() {
    return {
      loginData: {
        userName: "",
        password: "",
      },
      rules: {
        userName: [{ validator: this.validateUsername, trigger: "blur" }],
        password: [{ validator: this.validatePassword, trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState(["userinfo"]),
  },
  methods: {
    ...mapActions([LOGIN]),
    validateUsername(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    },

    validatePassword(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this[LOGIN]({
            user_name: this.loginData.userName,
            user_pwd: this.loginData.password,
          }).then((res) => {
            // console.log(res);
            if (res) {
              console.log(routers);
              // let arr = FilterRoutes(routers, this.userinfo.identity_text);
              // this.$router.addRoutes(arr);

              this.$router.replace("/home/homes");
            } else {
              alert("账号密码错误");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  width: 350px;
  background: #fff;
  border: 1px solid #409ecc;
  padding: 20px 30px;
  border-radius: 10px;
  .title {
    height: 40px;
    font-size: 20px;
    color: #409eff;
  }
}
</style>